//
//  HomePage_detailed_Controller.m
//  Food
//
//  Created by dllo on 15/7/13.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "HomePage_detailed_Controller.h"
#import "BaseHeader.h"
#import "HomePage_detailed_Cell.h"
#import "AFNetworkHandler.h"
#import "UIImageView+WebCache.h"
#import "HomePage_detailed_model.h"
#import "MJRefresh.h"
#import "HomePage_display_Controller.h"
#import "MBProgressHUD.h"
static int i = 1;
@interface HomePage_detailed_Controller () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) UIScrollView *scrollView;

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) NSMutableArray *arry;

@property (nonatomic, retain) UISegmentedControl *seg;

@end

@implementation HomePage_detailed_Controller

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"naviBack"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    
    self.navigationItem.title = self.naviTitle;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backGround.jpg"]];
    
    [self createScrollView];
    
    [self createCollectionView];
    
    [self addFooter];
    
//    [self performSelector:@selector(fun) withObject:self afterDelay:1];
    [self fun];
    
}

- (void) back
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBar.translucent = NO;
}


- (void) createScrollView
{
    NSMutableArray *arry = [NSMutableArray array];
    for (NSDictionary *dic in self.dataArry) {
        [arry addObject:dic[@"name"]];
    }
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 35)];
    self.scrollView.backgroundColor = [UIColor whiteColor];
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backGround.jpg"]];
    self.scrollView.contentSize = CGSizeMake(80 * arry.count, 35);
    [self.view addSubview:self.scrollView];
    
    self.seg = [[UISegmentedControl alloc] initWithItems:arry];
    self.seg.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backGround.jpg"]];
    self.seg.frame = CGRectMake(0, 0, 80 * arry.count, 35);
    self.seg.tintColor = [UIColor grayColor];
    self.seg.selectedSegmentIndex = 0;
    [self.seg addTarget:self action:@selector(fun) forControlEvents:UIControlEventValueChanged];
    
    [self.scrollView addSubview:self.seg];
}

- (void) createCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((ScreenWidth - 30) / 2.0, 120.0 / 375 * ScreenWidth);
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
    layout.minimumLineSpacing = 5;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.scrollView.frame.size.height, ScreenWidth, ScreenHeight - 64 - 35 - 49) collectionViewLayout:layout];
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.collectionView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backGround.jpg"]];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[HomePage_detailed_Cell class] forCellWithReuseIdentifier:@"cell"];
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HomePage_detailed_Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    HomePage_detailed_model *model = self.arry[indexPath.item];
    [cell setModel:model];
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arry.count;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    HomePage_display_Controller *display = [[HomePage_display_Controller alloc] init];
    HomePage_detailed_model *model = self.arry[indexPath.item];
    display.classid = model.classId;
    display.classTitle = model.name;
    display.MVBackGroundimage = model.imagePath;
    [self.navigationController pushViewController:display animated:YES];
}

#warning fun
- (void)fun
{
    
    i = 1;
    NSInteger index = self.seg.selectedSegmentIndex;
    NSDictionary *dic = self.dataArry[index];
    NSString *classId = dic[@"id"];
    self.navigationItem.title = dic[@"name"];
    self.arry = [NSMutableArray array];
    UIActivityIndicatorView *activityIndicator = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
    
    activityIndicator.frame = CGRectMake(0, 0, 100, 100);
    
    activityIndicator.color = [UIColor grayColor];
    
    activityIndicator.center = CGPointMake(ScreenWidth / 2.0, ScreenHeight / 2.0 - 50);
    
    [self.view addSubview:activityIndicator];
    
    [activityIndicator startAnimating];
    NSString *utlStr = [NSString stringWithFormat:@"http://121.41.84.91:80/HandheldKitchen/api/home/tblAssort!getVegetable.do?id=%@&page=1&pageRecord=10&is_traditional=0&phonetype=1", classId];
    [AFNetworkHandler getWithAFNByURL:utlStr completion:^(id result) {
        NSArray *tempArr =result[@"data"];
        self.arry = [HomePage_detailed_model arrayWithModelByArray:tempArr];
        [self.collectionView reloadData];
        [activityIndicator stopAnimating];
    }];
    
    
}

- (void) addFooter
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加上拉刷新尾部控件
    //[self.collectionView addFooterWithTarget:self action:@selector(footerAction)];
    [self.collectionView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        i++;
        [self getdata:i];
        // 模拟延迟加载数据，因此2秒后才调用）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [vc.collectionView reloadData];
            // 结束刷新
            [vc.collectionView footerEndRefreshing];
        });
    }];
}


//-(void)footerAction{
//
//    i++;
//    [self getdata:i];
//    // 模拟延迟加载数据，因此2秒后才调用）
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self.collectionView reloadData];
//        // 结束刷新
//        [self.collectionView footerEndRefreshing];
//    });
//
//}

- (void) getdata:(int)i
{
    
    UIActivityIndicatorView *activityIndicator = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
    
    activityIndicator.frame = CGRectMake(0, 0, 100, 100);
    
    activityIndicator.color = [UIColor grayColor];
    
    activityIndicator.center = CGPointMake(ScreenWidth / 2.0, ScreenHeight / 2.0 - 50);
    
    [self.view addSubview:activityIndicator];
    
    [activityIndicator startAnimating];
    
    NSInteger index = self.seg.selectedSegmentIndex;
    NSDictionary *dic = self.dataArry[index];
    NSString *classId = dic[@"id"];
    self.navigationItem.title = dic[@"name"];
    NSString *utlStr = [NSString stringWithFormat:@"http://121.41.84.91:80/HandheldKitchen/api/home/tblAssort!getVegetable.do?id=%@&page=%d&pageRecord=10&is_traditional=0&phonetype=1", classId, i];
    [AFNetworkHandler getWithAFNByURL:utlStr completion:^(id result) {
        NSArray *tempArr =result[@"data"];
        NSArray *tempArry = [HomePage_detailed_model arrayWithModelByArray:tempArr];
        for (HomePage_detailed_model *model in tempArry) {
            [self.arry addObject:model];
        }
        [self.collectionView reloadData];
        [activityIndicator stopAnimating];
        [self.collectionView footerEndRefreshing ];
    }];
}




//- (void)viewWillDisappear:(BOOL)animated
//{
//    self.view.window.alpha = 1.0;
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
